package cn.kgc.springbootdemo.config.task;

import cn.kgc.springbootdemo.service.UserRoleService;
import cn.kgc.springbootdemo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Set;

/**
 * <h3>springbootdemo</h3>
 * <p>定时任务</p>
 *
 * @author : DongZeJian
 * @date : 2020-06-23 11:30
 **/
@Configuration
/*@EnableScheduling*/
public class TestTask {
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private UserRoleService userRoleService;

    @Scheduled(cron = "0 0 12 * * ?")
    private void testTask(){
        System.out.println("执行静态定时任务时间: " + LocalDateTime.now());
    }


    @Scheduled(cron = "0 0/5 * * * ? ")
    private void findExpiredVip(){
        //获取所有vip的key
        Set<String> keys = redisUtil.keys("vip_*");
        //遍历所有key 获取对应失效时间
        keys.forEach(key->{
            //当前key剩余的秒数
            long s = redisUtil.ttl(key);
            //当秒数小于11分钟的时候删除该key
            if (s<11*60){
                redisUtil.del(key);
                //删除 用户角色关联表的会员信息
                String[] info = key.split("_");
                String userId = info[1];
                userRoleService.deleteOne(userId);
            }
        });
    }

}
